#!/bin/bash

file_server_dir="./novel_web_server/file_server"
read_server_dir="./novel_web_server/read_server"
main_server_dir="./novel_web_server"
pid_dir="$(pwd)/pids"

file_server="file_server"
read_server="read_server"
main_server="main_server"

max_retries=10
retries=0

function start_server {
    local dir=$1
    local server=$2
    local pid_file="$(pwd)/pids/$server.pid"

    (
        cd $dir
        ./$server &
        local pid=$!
        echo "Started $server in $dir with PID $pid"
        echo $pid > "$pid_file"  # Save PID to a file
    )
}



function check_server {
    local dir=$1
    local server=$2
    local pid_file="$(pwd)/pids/$server.pid"

    if [ -e "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null; then
            return 0  # Server is running
        fi
    fi

    return 1  # Server is not running
}


function restart_server {
    local dir=$1
    local server=$2

    while [ $retries -lt $max_retries ]; do
        check_server $dir $server
        if [ $? -eq 1 ]; then
            echo "Restarting $server in $dir"
            start_server $dir $server
            sleep 1  # Wait for the server to start
        else
            break
        fi
        ((retries++))
    done
    if [ $retries -eq $max_retries ]; then  
        echo "Failed to restart $server in $dir after $max_retries attempts. Stopping all servers."
        stop_all_servers
    fi
}

function stop_all_servers {
    echo "Stopping all servers"
    pkill -f "$file_server"
    pkill -f "$read_server"
    pkill -f "$main_server"
    rm -rf "$pid_dir"  # Remove the PID directory
    exit 0
}

trap 'stop_all_servers' INT TERM

# Create the PID directory
mkdir -p "$pid_dir"

# Start servers
start_server $file_server_dir $file_server
start_server $read_server_dir $read_server
start_server $main_server_dir $main_server

while true; do
    # Check servers
    check_server $file_server_dir $file_server || restart_server $file_server_dir $file_server
    check_server $read_server_dir $read_server || restart_server $read_server_dir $read_server
    check_server $main_server_dir $main_server || restart_server $main_server_dir $main_server

    sleep 5
done
